package com.ibeeking.found.cop.b.rest.service.mq;

import com.ibeeking.found.common.utils.DateUtils;
import com.ibeeking.found.cop.b.rest.service.IGroupQrcodeService;
import com.ibeeking.found.cop.b.rest.service.IGroupService;
import com.ibeeking.found.cop.b.rest.service.IGroupWelcomeService;
import com.ibeeking.found.cop.b.rest.service.IWxOpenService;
import com.ibeeking.found.cop.service.common.param.GroupAdminsParam;
import com.ibeeking.found.cop.service.common.param.GroupFriendsParam;
import com.ibeeking.found.cop.service.common.param.GroupParam;
import com.ibeeking.found.cop.service.common.param.MqSyncCopParam;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.date.DateUtil;
import com.ibeeking.nematos.utils.json.JsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpSchoolUserService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalGroupChatInfo;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalGroupChatList;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CopGroupMqConsumerHandler {

    @Resource
    private IGroupService groupServiceImpl;

    @Resource
    private IGroupWelcomeService groupWelcomeServiceImpl;

    @Resource
    private IGroupQrcodeService groupQrcodeServiceImpl;

    @Resource
    private IWxOpenService wxOpenServiceImpl;

    public boolean addAndUpdateGroupWelcome(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        Long tenantId = mqParam.getTenantId();
        Long msgId = mqParam.getId();
        String operType= mqParam.getOperType();
        groupWelcomeServiceImpl.syncGroupWelcomeToWxCp(tenantId.intValue(), msgId, false);
        return true;
    }
    public boolean delGroupWelcome(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        Long tenantId = mqParam.getTenantId();
        Long msgId = mqParam.getId();
        String operType= mqParam.getOperType();
        groupWelcomeServiceImpl.syncGroupWelcomeToWxCp(tenantId.intValue(), msgId, true);
        return true;
    }

    public boolean syncGrouplistFromWxcp(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        try {
            Long tenantId = mqParam.getTenantId();
            WxCpService wxCpService = wxOpenServiceImpl.getWxCpService(tenantId);
            WxCpConfigStorage wxCpConfigStorage = wxCpService.getWxCpConfigStorage();
            if (wxCpConfigStorage == null) {
                throw new BusinessException("获取企微服务失败!");
            }
            LogUtils.info("====process wxCpConfigStorage:{}====", JsonUtils.toJsonStr(wxCpConfigStorage));
            String corpId = wxCpConfigStorage.getCorpId();

            WxCpExternalContactService wxCpExternalContactService = wxCpService.getExternalContactService();
            if (wxCpExternalContactService == null) throw new BusinessException("获取企微服务外部联系人服务!");
            WxCpUserExternalGroupChatList wxCpUserExternalGroupChatList = wxCpExternalContactService.listGroupChat(1000,null,0,null);

            LogUtils.info("====WxCpUserExternalGroupChatList:{}====", JsonUtils.toJsonStr(wxCpUserExternalGroupChatList));
            if(wxCpUserExternalGroupChatList != null) {
                List<WxCpUserExternalGroupChatList.ChatStatus> groupChatStatusList= wxCpUserExternalGroupChatList.getGroupChatList();
                if (Collections3.isNotEmpty(groupChatStatusList)) {
                    List<GroupParam> allGroupParams = new ArrayList<>();
                    for(WxCpUserExternalGroupChatList.ChatStatus groupChatIdStatus:groupChatStatusList){
                        String chatId = groupChatIdStatus.getChatId();
                        Integer chatStatus = groupChatIdStatus.getStatus();
                        if(StringUtils.isNotEmpty(chatId)){
                            WxCpUserExternalGroupChatInfo wxCpUserExternalGroupChatInfo = wxCpExternalContactService.getGroupChat(chatId, 1);
                            LogUtils.info("====wxCpUserExternalGroupChatInfo:{}====", JsonUtils.toJsonStr(wxCpUserExternalGroupChatInfo));
                            if(wxCpUserExternalGroupChatInfo !=null){
                                WxCpUserExternalGroupChatInfo.GroupChat groupChat = wxCpUserExternalGroupChatInfo.getGroupChat();

                                if(groupChat != null){
                                    GroupParam groupParam = new GroupParam();
                                    List<WxCpUserExternalGroupChatInfo.GroupAdmin> groupAdminList = groupChat.getAdminList();
                                    List<WxCpUserExternalGroupChatInfo.GroupMember> groupMemberList = groupChat.getMemberList();
                                    groupParam.setChatId(chatId);
                                    groupParam.setStatus(chatStatus);
                                    groupParam.setName(groupChat.getName());
                                    groupParam.setNotice(groupChat.getNotice());
                                    groupParam.setOwnerCode(groupChat.getOwner());
                                    if(groupChat.getCreateTime() != null) {
                                        LocalDateTime buidTime = DateUtil.longToLocalDateTime(groupChat.getCreateTime());
                                        groupParam.setBuildTime(DateUtils.localDateTimeToStr(buidTime));
                                    }
                                    if(Collections3.isNotEmpty(groupAdminList)){
                                        List<GroupAdminsParam> groupAdminsList = new ArrayList<>();
                                        for(WxCpUserExternalGroupChatInfo.GroupAdmin groupAdmin:groupAdminList){
                                            GroupAdminsParam groupAdmins = new GroupAdminsParam();
                                            groupAdmins.setEmployeeCode(groupAdmin.getUserId());
                                            groupAdmins.setChatId(chatId);
                                            groupAdminsList.add(groupAdmins);
                                        }
                                        groupParam.setGroupAdminsList(groupAdminsList);
                                    }
                                    if(Collections3.isNotEmpty(groupMemberList)){
                                        List<GroupFriendsParam> groupFriendsList = new ArrayList<>();
                                        for(WxCpUserExternalGroupChatInfo.GroupMember groupMember:groupMemberList){
                                            GroupFriendsParam groupFriends = new GroupFriendsParam();
                                            groupFriends.setChatId(chatId);
                                            String friendsCode = groupMember.getUserId();
                                            groupFriends.setFriendsCode(friendsCode);
                                            groupFriends.setFriendsName(groupMember.getName());
                                            groupFriends.setFriendsGroupNickname(groupMember.getGroupNickname());
                                            groupFriends.setFriendsType(groupMember.getType());
                                            groupFriends.setFriendsJoinScene(groupMember.getJoinScene());
                                            if(groupMember.getJoinTime() != null) {
                                                LocalDateTime joinTime = DateUtil.longToLocalDateTime(groupMember.getJoinTime());
                                                groupFriends.setFriendsJoinTime(DateUtil.localDateTimeToStr(joinTime));
                                            }
                                            groupFriends.setFriendsUnionid(groupMember.getUnionId());

                                            if(groupMember.getInvitor() != null) {
                                                groupFriends.setInvitorCode(groupMember.getInvitor().getUserId());
                                            }
                                            groupFriends.setState(groupMember.getState());
                                            groupFriendsList.add(groupFriends) ;
                                        }
                                        groupParam.setGroupFriendsList(groupFriendsList);
                                    }
                                    allGroupParams.add(groupParam);
                                }
                            }
                        }
                    }
                    LogUtils.info("====allGroupParams:{}====", JsonUtils.toJsonStr(allGroupParams));
                    if(Collections3.isNotEmpty(allGroupParams)){
                        groupServiceImpl.saveOrUpdateOrDeleteBatchGroups(tenantId,allGroupParams);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            LogUtils.error("同步部门信息任务处理异常:{}", e);
            return false;
        }
    }

    public boolean syncGroupAddJoinWay(MqSyncCopParam mqParam, Map<String, Object> extMap) {
        Long tenantId = mqParam.getTenantId();
        Long qrcodeId = mqParam.getId();
        String operType= mqParam.getOperType();
        groupQrcodeServiceImpl.wxCpProcessGroupAddJoinWay(tenantId.intValue(), qrcodeId, operType);
        return true;
    }

}
